import requests
from playwright.sync_api import sync_playwright
import re
import time
import datetime



class MaoyanCralwer():
    def __init__(self) -> None:
        self.user_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36'
        self.random = 9
        self.timestamp = None
        self.browser = None
        self.page=None
        self.cookies = None
    
    def reqInfo(self,movie_id):
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Pragma': 'no-cache',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': self.user_agent,
            'X-Requested-With': 'XMLHttpRequest',
            'sec-ch-ua': '"Not-A.Brand";v="24", "Chromium";v="14"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        self.timestamp = int(datetime.datetime.now().timestamp()*1000)
        signKey = self.generateSignKey()
        params = {
            'timeStamp': self.timestamp,
            'index': self.random,
            'signKey': signKey,
            'channelId': '40011',
            'sVersion': '1',
            'webdriver': 'false',
        }

        response = requests.get(
            f'https://www.maoyan.com/ajax/films/{movie_id}',
            headers=headers,params=params,cookies=self.cookies
        )
        return response.text
    
    def generateSignKey(self):
        if not self.browser:
            playwright = sync_playwright().start()
            browser_type = playwright.chromium
            self.browser = browser_type.launch(headless=False,args=["--disable-blink-features=AutomationControlled"])
            context = self.browser.new_context()
            self.page = context.new_page()
            def handle_js(route):
                if re.search(r'common\.\w+\.js', route.request.url):
                    response = route.fetch()
                    content = response.body()
                    content = content.replace(b'n[r(_0x5bfb("0x183"))]=16,', b'n[r(_0x5bfb("0x183"))]=16,window.uuuu=')
                    route.fulfill(body=content)
                else:
                    route.continue_()
            self.page.set_default_timeout(0)        
            self.page.route("**/*.js", handle_js)
            self.page.goto(f'https://www.maoyan.com/films/1452790')
            self.transformCookie(context.cookies())
        message = f'method=GET&timeStamp={self.timestamp}&User-Agent={self.user_agent}&index={self.random}&channelId=40011&sVersion=1&key=A013F70DB97834C0A5492378BD76C53A'
        signature = self.page.evaluate(f'window.uuuu("{message}")')
        return signature
    
    def transformCookie(self,cookies_list):
        self.cookies = { c['name']:c['value'] for c in cookies_list}

    

maoyanCralwer=MaoyanCralwer() 

res = maoyanCralwer.reqInfo('1470379')
print(res)
pass